//
//  XMNetwork.m
//  XMJJ_zml
//
//  Created by apple on 2025/5/7.
//

#import "XMNetwork.h"
#import <AFNetworking.h>
#import "XMLoginOtherPhoneController.h"

@interface XMNetwork ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation XMNetwork

static XMNetwork *network;
static dispatch_once_t onceToken;
+ (instancetype)shareInstance {
    if (!network) {
        dispatch_once(&onceToken, ^{
            network = [[XMNetwork alloc] init];
        });
    }
    return network;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _manager = [[AFHTTPSessionManager alloc] init];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        [_manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        _manager.requestSerializer.timeoutInterval = 10;
        [_manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"tenant-id"];
    }
    return self;
}

- (void)getDataWithPath:(NSString *)path
             parameters:(NSMutableDictionary *)parameters
              needToken:(BOOL)needToken
                headers:(NSDictionary *)headers
                success:(void (^)(id responseObject))successBlock
                failure:(void (^)(NSError *error))failureBlock {
    [self getDataWithPath:path
               parameters:parameters
                needToken:needToken
                  headers:headers
          showPrograssHUD:YES
                  success:successBlock
                  failure:failureBlock];
}

- (void)postDataWithPath:(NSString *)path
              parameters:(NSMutableDictionary *)parameters
               needToken:(BOOL)needToken
                 headers:(NSDictionary *)headers
                 success:(void (^)(id responseObject))successBlock
                 failure:(void (^)(NSError *error))failureBlock {
    [self postDataWithPath:path
                parameters:parameters
                 needToken:needToken
                   headers:headers
           showPrograssHUD:YES
                   success:successBlock
                   failure:failureBlock];
}

/**
 Get 不带菊花
 */
- (void)getDataWithPath:(NSString *)path
             parameters:(NSMutableDictionary *)parameters
              needToken:(BOOL)needToken
                headers:(NSDictionary *)headers
        showPrograssHUD:(BOOL)showProgressHud
                success:(void (^)(id _Nonnull))successBlock
                failure:(void (^)(NSError * _Nonnull))failureBlock {
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
    NSMutableDictionary *newHeadDic = [NSMutableDictionary dictionaryWithDictionary:headers];
    if (needToken) {
        if (needToken && userModel && userModel.refreshToken.length > 0) {
            [newHeadDic safe_setObject:userModel.refreshToken forKey:@"Authorization"];
//            [parameters safe_setObject:userModel.token forKey:@"token"];
//            [parameters safe_setObject:@"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpdC5kanhzLm1jbGFuZGlhbi5jb21cL2xvZ2luIiwiaWF0IjoxNjQ4Njg5ODkwLCJleHAiOjE2NTEyODE4OTAsIm5iZiI6MTY0ODY4OTg5MCwianRpIjoicW9tWno1OWhWWmpWSEZVTCIsInN1YiI6NjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEiLCJyb2xlIjoidXNlciJ9.WC-a1K-laExlWBX-1Y8_k7HTOrDpcpNWaaHZ1gARJ0M" forKey:@"token"];
        }
        else {
            XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
            if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
                XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
                UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
                loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [currentVC presentViewController:loginNVC animated:YES completion:nil];
                return;
            }
        }
    }
    else {
        if (userModel && userModel.refreshToken.length > 0) {
            [newHeadDic safe_setObject:userModel.refreshToken forKey:@"Authorization"];
        }
    }
    
    NSString *requestUrl;
    if ([path containsString:@"http"]) {
        requestUrl = path;
    }
    else {
        requestUrl = [NSString stringWithFormat:@"%@/%@", baseUrl, path];
    }
    XMWeakSelf;
    if (showProgressHud) {
        [MBProgressHUD showMessage:@"加载中..." toView:[UIApplication sharedApplication].keyWindow];
    }
    [_manager GET:requestUrl
       parameters:parameters
          headers:newHeadDic
         progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        if ([requestUrl containsString:baseUrl]) {
            [weakSelf analysisData:responseObject showPrograssHUD:showProgressHud requestUrl:path success:successBlock failure:failureBlock];
        }
        else {
            successBlock (responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        failureBlock (error);
    }];
}

/**
 Post  不带菊花
 */
- (void)postDataWithPath:(NSString *)path
              parameters:(NSMutableDictionary *)parameters
               needToken:(BOOL)needToken
                 headers:(NSDictionary *)headers
         showPrograssHUD:(BOOL)showProgressHud
                 success:(void (^)(id responseObject))successBlock
                 failure:(void (^)(NSError *error))failureBlock {
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
    NSMutableDictionary *newHeadDic = [NSMutableDictionary dictionaryWithDictionary:headers];
    if (needToken) {
        if (needToken && userModel && userModel.refreshToken.length > 0) {
            [newHeadDic safe_setObject:userModel.refreshToken forKey:@"Authorization"];
        }
        else {
            XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
            if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
                XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
                UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
                loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [currentVC presentViewController:loginNVC animated:YES completion:nil];
                return;
            }
        }
    }
    else {
        if (userModel && userModel.refreshToken.length > 0) {
            [newHeadDic safe_setObject:userModel.refreshToken forKey:@"Authorization"];
        }
    }
    NSString *requestUrl = @"";
    if ([path containsString:@"http"]) {
        requestUrl = path;
    }
    else {
        requestUrl = [NSString stringWithFormat:@"%@/%@", baseUrl, path];
    }
    [newHeadDic setValue:@"1" forKey:@"tenant-id"];
    XMWeakSelf;
    if (showProgressHud) {
        [MBProgressHUD showMessage:@"提交中..." toView:[UIApplication sharedApplication].keyWindow];
    }
//    [parameters safe_setObject:@"1" forKey:@"scene"];
    [_manager POST:requestUrl
        parameters:parameters
           headers:newHeadDic
          progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        [weakSelf analysisData:responseObject showPrograssHUD:showProgressHud requestUrl:path success:successBlock failure:failureBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        failureBlock (error);
    }];
}

/**
 put
 */
- (void)putDataWithPath:(NSString *)path
             parameters:(NSMutableDictionary *)parameters
              needToken:(BOOL)needToken
                headers:(NSDictionary *)headers
        showPrograssHUD:(BOOL)showProgressHud
                success:(void (^)(id _Nonnull))successBlock
                failure:(nonnull void (^)(NSError * _Nonnull))failureBlock {
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
    NSMutableDictionary *newHeadDic = [NSMutableDictionary dictionaryWithDictionary:headers];
    if (needToken) {
        if (needToken && userModel && userModel.refreshToken.length > 0) {
            [newHeadDic safe_setObject:userModel.refreshToken forKey:@"Authorization"];
        }
        else {
            XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
            if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
                XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
                UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
                loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [currentVC presentViewController:loginNVC animated:YES completion:nil];
                return;
            }
        }
    }
    NSString *requestUrl = @"";
    if ([path containsString:@"http"]) {
        requestUrl = path;
    }
    else {
        requestUrl = [NSString stringWithFormat:@"%@/%@", baseUrl, path];
    }
    [newHeadDic setValue:@"1" forKey:@"tenant-id"];
    XMWeakSelf;
    [_manager PUT:requestUrl
       parameters:parameters
          headers:newHeadDic
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        [weakSelf analysisData:responseObject showPrograssHUD:showProgressHud requestUrl:path success:successBlock failure:failureBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        failureBlock (error);
    }];
}

//解析数据
- (void)analysisData:(NSDictionary *)responseObject
     showPrograssHUD:(BOOL)showProgressHud
          requestUrl:(NSString *)requestStr
             success:(void (^)(id responseObject))successBlock
             failure:(void (^)(NSError *error))failureBlock {
    if (responseObject) {
        NSInteger codeResult = [responseObject safeIntegerForKey:@"code"];
        if (codeResult == 0) {
//            NSString *statusStr = [responseObject objectForKey:@"status"];
//            if (![statusStr isEqualToString:@"success"]) {
//                if (showProgressHud) {
//                    [MBProgressHUD showError:[responseObject objectForKey:@"msg"] toView:[UIApplication sharedApplication].keyWindow];
//                }
//                NSLog(@"调通 返回error");
//                NSLog(@"%@", [responseObject safeStringForKey:@"msg"]);
//                failureBlock(nil);
//                return;
//            }
//            else {
           successBlock (responseObject);
//            }
        }
        else {
            NSLog(@"token失效");
            NSLog(@"跳登陆");
            NSString *errorStr = [responseObject safeStringForKey:@"msg"];
 
            if (![requestStr containsString:@""] && [errorStr isEqualToString:@"账号未登录"]) {
//                [[DJUserManager shareInstance] removeUser];
                XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
                if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
                    [MBProgressHUD showError:@"登录已过期，请重新登录"];
                    XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
                    UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
                    loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
                    [currentVC presentViewController:loginNVC animated:YES completion:nil];
                    return;
                }
            }
            NSError *error = [NSError errorWithDomain:@""
                                                 code:codeResult
                                             userInfo:@{
                                                 NSLocalizedDescriptionKey: errorStr,
                                                 NSLocalizedRecoverySuggestionErrorKey: @"请稍后再试"
                                             }];
            if (showProgressHud) {
                if (errorStr && errorStr.length > 0) {
                    [MBProgressHUD showError:errorStr];
                }
                else {
                    [MBProgressHUD showError:@"请求错误"];
                }
            }
            
             failureBlock(error);
            return;
        }
    }
    else {
        NSLog(@"返回的数据格式错误");
        failureBlock(nil);
        return;
    }
}

//单张
- (void)upLoadImgWithPath:(NSString *)path
                      img:(UIImage *)img
                  success:(void (^)(id responseObject))successBlock
                  failure:(void (^)(NSError *error))failureBlock {
    //完善URL
    //拼接token
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
//    NSString *tokenStr = userModel.token;
    NSMutableDictionary *sParameters = [NSMutableDictionary dictionary];
    NSMutableDictionary *heads = [NSMutableDictionary dictionary];
    if (userModel && userModel.refreshToken.length > 0) {
        [heads safe_setObject:userModel.refreshToken forKey:@"Authorization"];
    }
    else {
        XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
        if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
            XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
            UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
            loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
            [currentVC presentViewController:loginNVC animated:YES completion:nil];
            return;
        }
    }
    [heads setValue:@"1" forKey:@"tenant-id"];
    NSString *requestUrl = [NSString stringWithFormat:@"%@/%@", baseUrl, path];
    [_manager POST:requestUrl
         parameters:sParameters
            headers:heads
constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *imgData = UIImagePNGRepresentation(img);
        NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
//        NSLog(@"%ld", imgData.length);
//        if (imgData.length >= 0.1*(1024*1024)) {
//            NSString *mbStr = [NSString stringWithFormat:@"%.1fM", imgData.length/1024/1024.0];
//        }
//        else if (imgData.length >= 1024) {
//            NSString *kbStr = [NSString stringWithFormat:@"%0.0fK", imgData.length/1024.0];
//        }
        [formData appendPartWithFileData:imgData name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
    }
           progress:^(NSProgress * _Nonnull uploadProgress) {
    }
            success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            [self analysisData:responseObject showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
        }
        else {
            NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            if ([jsonStr hasPrefix:@"("]) {
                jsonStr = [jsonStr substringFromIndex:1];
                jsonStr = [jsonStr substringToIndex:jsonStr.length - 2];
                
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];
                [self analysisData:dictionary showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
            }
            else {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingFragmentsAllowed error:nil];
                [self analysisData:dic showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
            }
        }
    }
            failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        failureBlock (error);
    }];
}

//多张
- (void)upLoadImgsWithPath:(NSString *)path
                parameters:(NSMutableDictionary *)parameters
                       img:(NSArray *)imgArr
                   success:(void (^)(id _Nonnull))successBlock
                   failure:(void (^)(NSError * _Nonnull))failureBlock {
    //拼接token
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
    NSMutableDictionary *heads = [NSMutableDictionary dictionary];
    if (userModel && userModel.refreshToken.length > 0) {
        [heads safe_setObject:userModel.refreshToken forKey:@"Authorization"];
    }
    else {
        XMBaseViewController *currentVC = (XMBaseViewController *)[AppDelegate getCurrentVC];
        if (![currentVC isKindOfClass:[XMLoginOtherPhoneController class]]) {
            XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
            UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
            loginNVC.modalPresentationStyle = UIModalPresentationFullScreen;
            [currentVC presentViewController:loginNVC animated:YES completion:nil];
            return;
        }
    }
    [heads setValue:@"1" forKey:@"tenant-id"];
    NSString *requestUrl = [NSString stringWithFormat:@"%@/%@", baseUrl, path];
    [_manager POST:requestUrl
         parameters:parameters
            headers:heads
constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < imgArr.count; i ++) {
            UIImage *img = imgArr[i];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
            [formData appendPartWithFileData:imgData
                                        name:@"files"
                                    fileName:[NSString stringWithFormat:@"file[%d]", i]
                                    mimeType:@"image/jpeg"];
        }
    }
           progress:^(NSProgress * _Nonnull uploadProgress) {
    }
            success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            [self analysisData:responseObject showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
        }
        else {
            NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            if ([jsonStr hasPrefix:@"("]) {
                jsonStr = [jsonStr substringFromIndex:1];
                jsonStr = [jsonStr substringToIndex:jsonStr.length - 2];
                
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];
                [self analysisData:dictionary showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
            }
            else {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingFragmentsAllowed error:nil];
                [self analysisData:dic showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
            }
        }
    }
            failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        failureBlock (error);
    }];
}

////单张
//- (void)upLoadImgWithPath:(NSString *)path
//                      img:(UIImage *)img
//                  success:(void (^)(id responseObject))successBlock
//                  failure:(void (^)(NSError *error))failureBlock {
//    //完善URL
//    //拼接token
////    DJUserModel *userModel = [[DJUserManager shareInstance] getUser];
////    NSString *tokenStr = userModel.token;
//    NSMutableDictionary *sParameters = [NSMutableDictionary dictionary];
////    if (tokenStr && tokenStr.length > 0) {
////        [sParameters safe_setObject:tokenStr forKey:@"token"];
////    }
//    NSString *requestUrl = [NSString stringWithFormat:@"%@/%@/%@", baseUrl, version, path];
//    [_manager POST:requestUrl
//         parameters:sParameters
//            headers:@{}
//constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
////        NSData *imgData = UIImagePNGRepresentation(img);
//        NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
////        NSLog(@"%ld", imgData.length);
////        if (imgData.length >= 0.1*(1024*1024)) {
////            NSString *mbStr = [NSString stringWithFormat:@"%.1fM", imgData.length/1024/1024.0];
////        }
////        else if (imgData.length >= 1024) {
////            NSString *kbStr = [NSString stringWithFormat:@"%0.0fK", imgData.length/1024.0];
////        }
//        [formData appendPartWithFileData:imgData name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
//    }
//           progress:^(NSProgress * _Nonnull uploadProgress) {
//    }
//            success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
//        if ([responseObject isKindOfClass:[NSDictionary class]]) {
//            [self analysisData:responseObject showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
//        }
//        else {
//            NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//            if ([jsonStr hasPrefix:@"("]) {
//                jsonStr = [jsonStr substringFromIndex:1];
//                jsonStr = [jsonStr substringToIndex:jsonStr.length - 2];
//
//                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];
//                [self analysisData:dictionary showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
//            }
//            else {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingFragmentsAllowed error:nil];
//                [self analysisData:dic showPrograssHUD:YES requestUrl:requestUrl success:successBlock failure:failureBlock];
//            }
//        }
//    }
//            failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
//        failureBlock (error);
//    }];
//}

@end
